package a66weding.com.jiehuntong.pager;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ToolsDayPlanActivity;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.DayplanTask;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.WedPlanTypeBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.fragment.BaseFragment;
import a66weding.com.jiehuntong.fragment.IFragmentCallBack;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.http.XutilHttp;
import a66weding.com.jiehuntong.widgets.wheelview.OnWheelChangedListener;
import a66weding.com.jiehuntong.widgets.wheelview.WheelView;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.NumericWheelAdapter;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/6/2
 * @description :
 */
public class ToolsPager_DayPlan_addTask extends BaseFragment implements View.OnClickListener,OnNetResultListener, OnWheelChangedListener {
    private ToolsDayPlanActivity mTaskActivity;
    private View mContentView;
    private ListView mTaskLv;
    private List<WedPlanTypeBean.DataBean> mTypeList;
    private RelativeLayout mTypeModelv;
    private RelativeLayout mTypeTimelv;

    //时间选择
    private WheelView mViewHour;
    private WheelView mViewMin;

    private PopupWindow mTimePopupWindow;

    private String mTypeName;
    private Button mCommitBtn;
    private EditText mAddPersonEt;
    private EditText mAddContentEt;
    private RelativeLayout mEditType;
    private TextView mSelectTime;
    private TextView mEditTypeTv;
    private TextView mSelecTypeTv;
    private TextView mHeadRightTv;
    private TextView mEditTypeNameTv;

    private  WedPlanTypeBean.DataBean mTypeBean;
    private int weddingProcessClassID;

    private int hour;
    private int minute;
    private int mSelectHour;
    private int mSelectMin;
    private String taskTime;
    private boolean isEdit;
    private DayplanTask.DataBean childData;
    private WedPlanTypeBean.DataBean dataBean;
    private TextView mTitleTv;
    private TextView mBackTv;
    private String weddingProcessClassName;
    private int weddingProcessID;
    private int groupPosition;
    private static IFragmentCallBack callBack;

    private boolean isEditAdd;

    private boolean isFirstEditAdd;

    private int mCurrentChildPosition;

    public static ToolsPager_DayPlan_addTask newInstance(IFragmentCallBack callBack2) {
        ToolsPager_DayPlan_addTask frag = new ToolsPager_DayPlan_addTask();
        callBack=callBack2;
        return frag;
    }


    @Override
    public View initView() {
        mTaskActivity = (ToolsDayPlanActivity) getActivity();
        mContentView = View.inflate(mTaskActivity, R.layout.pager_tools_dayplan_addtask, null);
        mTitleTv = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_title);
        mBackTv = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_backcontent);
        mAddPersonEt = (EditText) mContentView.findViewById(R.id.et_tools_dayplan_personadd);
        mAddContentEt = (EditText) mContentView.findViewById(R.id.et_tools_dayplan_editcontent);
        mSelectTime = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_time);
        mEditType = (RelativeLayout) mContentView.findViewById(R.id.rlay_tools_dayplan_ready);//修改类型名称Lay
        mEditTypeTv = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_edittype);//修改类型
        mSelecTypeTv = (TextView) mContentView.findViewById(R.id.tv_tools_ready);//选择类型
        mHeadRightTv = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_addtype1);//选择类型
        mEditTypeNameTv = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_edittype);//修改类型名称TextView

        //完成，提交
        mCommitBtn = (Button) mContentView.findViewById(R.id.btn_tools_dayplan_addtaskcommit);

        LinearLayout mBackLay = (LinearLayout) mContentView.findViewById(R.id.llay_toolsheader_back);//头部返回

        mTypeModelv = (RelativeLayout) mContentView.findViewById(R.id.rlay_tools_dayplanmodel);
        mTypeTimelv = (RelativeLayout) mContentView.findViewById(R.id.rlay_tools_dayplan_time);

        mBackTv.setText("返回");
        mHeadRightTv.setVisibility(View.GONE);

        mBackLay.setOnClickListener(this);
        mTypeModelv.setOnClickListener(this);
        mCommitBtn.setOnClickListener(this);
        mTypeTimelv.setOnClickListener(this);
        return mContentView;
    }

    @Override
    public void initData() {

        mTypeList = mTaskActivity.getmTypeList();

        groupPosition = mTaskActivity.getmCurrentGroupPosition();

        dataBean = mTypeList.get(groupPosition);
        weddingProcessClassID= dataBean.getWeddingProcessClassID();

        weddingProcessClassName = mTypeList.get(groupPosition).getWeddingProcessClassName();
        isEdit = mTaskActivity.isEditType();

        if(isEdit) {
            mTitleTv.setText("修改流程类型");
        }else{
            mTitleTv.setText("添加新流程");
        }

        if(isEdit) {
            mCurrentChildPosition= mTaskActivity.getmCurrentChildPosition();
            DayplanTask.DataBean dataBean = this.dataBean.getTaskData().get(mCurrentChildPosition);
            weddingProcessID = dataBean.getWeddingProcessID();

            mEditType.setVisibility(View.VISIBLE);
            mEditType.setOnClickListener(this);

            mEditTypeNameTv.setText(weddingProcessClassName);
            mSelecTypeTv.setText(weddingProcessClassName);

            childData = this.dataBean.getTaskData().get(mCurrentChildPosition);
            mAddPersonEt.setText(childData.getWeddingProcessMan());
            mSelectTime.setText(childData.getWeddingProcessTime());
            mAddContentEt.setText(childData.getWeddingProcessThing());

            List<DayplanTask.DataBean> taskData = mTypeList.get(groupPosition).getTaskData();

        }else{

            mEditType.setVisibility(View.GONE);
            mSelecTypeTv.setText(weddingProcessClassName);
            mAddPersonEt.setText(null);
            mAddPersonEt.setHint("输入流程中的重要参与人员");
            mSelectTime.setText("00:00");
            mAddContentEt.setText(null);
            mAddContentEt.setHint("输入流程概要");

        }
        mContentView.invalidate();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

                case R.id.llay_toolsheader_back:
//                    mTaskActivity.setContentClickable(true);
                    mTaskActivity.getSupportFragmentManager().popBackStackImmediate();
                    break;

                case R.id.rlay_tools_dayplanmodel://类型选择
                    showPopupWindow(view);
                    break;

                case R.id.rlay_tools_dayplan_time://时间选择
                    showtimePopupWindow(view);

                    break;
                case R.id.btn_tools_dayplan_addtaskcommit:
                    //检验Edittext格式
                    boolean b = checEditkword();
                    if(b) {
                        //发送数据
//                        WeddingProcessID
                        if(isEditAdd){//编辑添加
                            commitAdd(view);
                        }
                        else if(isEdit) {//修改
                            commitEdit( view);
                        }else{//添加
                            commitAdd(view);
                        }

                    }

                    break;
                case R.id.tv_cancel://取消
                    if(mTimePopupWindow!=null) {
                        mTimePopupWindow.dismiss();
                    }

                    break;

                case R.id.tv_confim://确定

                    String taskTimeHour=mSelectHour+"";
                    if(mSelectHour<10) {
                        taskTimeHour="0"+mSelectHour;
                    }
                    String taskTimeMin=mSelectMin+"";
                    if(mSelectMin<10) {
                        taskTimeMin="0"+mSelectMin;
                    }

                    taskTime = taskTimeHour+":"+taskTimeMin;
                    mSelectTime.setText(taskTime);

                    if(mTimePopupWindow!=null) {
                        mTimePopupWindow.dismiss();
                    }
                    break;
                case R.id.rlay_tools_dayplan_ready://修改类型
                    mTaskActivity.setmCurrentGroupPosition(groupPosition);
                    callBack.jump("修改类型",this);

                    break;

        }

    }

    @Override
    public void onResume() {
        super.onResume();

        if(isEdit) {
            mEditType.setVisibility(View.VISIBLE);
            mEditType.setOnClickListener(this);

            int childPosition = mTaskActivity.getmCurrentChildPosition();
            mEditTypeNameTv.setText(weddingProcessClassName);
            mSelecTypeTv.setText(weddingProcessClassName);

            childData = dataBean.getTaskData().get(childPosition);
            mAddPersonEt.setText(childData.getWeddingProcessMan());
            mSelectTime.setText(childData.getWeddingProcessTime());
            mAddContentEt.setText(childData.getWeddingProcessThing());

        }else{

            mEditType.setVisibility(View.GONE);
            mSelecTypeTv.setText(weddingProcessClassName);
            mAddPersonEt.setText(null);
            mAddPersonEt.setHint("输入流程中的重要参与人员");
            mSelectTime.setText("00:00");
            mAddContentEt.setText(null);
            mAddContentEt.setHint("输入流程概要");

        }

    }

    private void commitEdit(View view){
        String persons = mAddPersonEt.getText().toString().trim();
        String content = mAddContentEt.getText().toString().trim();
        String time=taskTime;

        String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_WEDDINGPROCESS);

        HashMap<String,String> paramsMap =new HashMap<>();
        paramsMap.put("WeddingProcessClassID",String.valueOf(weddingProcessClassID));
        paramsMap.put("WeddingProcessClassName",weddingProcessClassName);
        paramsMap.put("WeddingProcessID",String.valueOf(weddingProcessID));
        paramsMap.put("WeddingProcessTime",time);
        paramsMap.put("WeddingProcessThing",content);
        paramsMap.put("WeddingProcessMan",persons);

        dataBean.setWeddingProcessClassName(weddingProcessClassName);
        childData.setWeddingProcessMan(persons);
        childData.setWeddingProcessTime(time);
        childData.setWeddingProcessThing(content);

        HttpRequestBean addTaskHttp=new HttpRequestBean(RequestCode.POSTEQUEST,url,this,
                CommonResultBean.class,RequestCode.UPDATE_WEDDINGPROCESS,paramsMap);

        HttpHandleUtil.executeCommonPost(mTaskActivity,addTaskHttp);

        showCommitPopupWindow2(view);
    }




    private void commitAdd(View view){

        String persons = mAddPersonEt.getText().toString().trim();

        String content = mAddContentEt.getText().toString().trim();

        String time=taskTime;

        String url= UrlDealUtil.getRealUrl(RequestCode.ADDWEDDINGPROCESS);

        HashMap<String,String> paramsMap =new HashMap<>();

        if(mTypeList.size() - 1 >= groupPosition){
            dataBean = mTypeList.get(groupPosition);
            weddingProcessClassID= dataBean.getWeddingProcessClassID();
        }
        paramsMap.put("WeddingProcessClassID",String.valueOf(weddingProcessClassID));
        paramsMap.put("WeddingProcessMan",persons);
        paramsMap.put("WeddingProcessTime",time);
        paramsMap.put("WeddingProcessThing",content);



        HttpRequestBean addTaskHttp=new HttpRequestBean(RequestCode.POSTEQUEST,url,this,
                CommonResultBean.class,RequestCode.ADDWEDDINGPROCESS,paramsMap);


        HttpHandleUtil.executeCommonPost(mTaskActivity,addTaskHttp);

        showCommitPopupWindow(view);
    }

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mTaskActivity).inflate(
                R.layout.pop_tools_dayplan_task, null);
        mTaskLv = (ListView) contentView.findViewById(R.id.lview_tools_dayplan_task);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)) );

        //点击空白处时，隐藏掉pop窗口
        popupWindow.setTouchable(true);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);


        //设置位置
        popupWindow.showAtLocation(mTypeModelv, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


        if (mTypeList != null) {
            mTaskLv.setAdapter(new CommonAdapter<WedPlanTypeBean.DataBean>(mTaskActivity, mTypeList, R.layout.item_tools_dayplan_tasktype) {

                @Override
                public void convert(MyViewHolder holder, int position) {
//                    String content = contentList.get(position);
                    String content = mTypeList.get(position).getWeddingProcessClassName();

                    holder.setText(R.id.tv_tools_dayplan_taskitem, content);

                }
            });

            mTaskLv.setOnItemClickListener(new ListView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    view.setBackgroundColor(mTaskActivity.getResources().getColor(R.color.colorMainRed));
                    mTypeName = mTypeList.get(position).getWeddingProcessClassName();
//                    weddingProcessClassID=mTypeList.get(position).getWeddingProcessClassID();
                    groupPosition=position;

                    mSelecTypeTv.setText(mTypeName);
                    mEditTypeNameTv.setText(mTypeName);
                    weddingProcessClassName=mTypeName;


                    popupWindow.dismiss();

                }
            });
        }


    }



    private void showtimePopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mTaskActivity).inflate(
                R.layout.pop_tools_dayplan_time, null);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_cancel);
        TextView mConfimTv = (TextView) contentView.findViewById(R.id.tv_confim);
        mViewHour = (WheelView) contentView.findViewById(R.id.id_hour);
        mViewMin = (WheelView) contentView.findViewById(R.id.id_minute);

        mCancelTv.setOnClickListener(this);
        mConfimTv.setOnClickListener(this);

        // 添加change事件
        mViewHour.addChangingListener(this);
        // 添加change事件
        mViewMin.addChangingListener(this);

        setUpData();


        mTimePopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        //点击空白处时，隐藏掉pop窗口
        mTimePopupWindow.setTouchable(true);

        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        mTimePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        mTimePopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    private void setUpData() {

        getTime();

        NumericWheelAdapter hourWheelAdapter = new NumericWheelAdapter(mTaskActivity, 0, 23);
        NumericWheelAdapter minWheelAdapter = new NumericWheelAdapter(mTaskActivity, 0, 59);

        mViewHour.setViewAdapter(hourWheelAdapter);
        mViewMin.setViewAdapter(minWheelAdapter);

        // 设置可见条目数量
        mViewHour.setVisibleItems(7);
        mViewMin.setVisibleItems(7);
        mViewHour.setCurrentItem(hour);
        mViewMin.setCurrentItem(minute);

        mViewHour.setCyclic(true);
        mViewMin.setCyclic(true);

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {

       if( wheel==mViewHour) {
            mSelectHour=newValue;
        }else if(wheel == mViewMin){
            mSelectMin=newValue;
        }

    }

    public void getTime(){
        Calendar c = Calendar.getInstance();
//        取得系统日期:
        //取得系统时间：
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);

    }






    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object objdata = sucessbean.getData();

        if(objdata instanceof CommonResultBean) {
            CommonResultBean commonresult = (CommonResultBean) objdata;
            switch (commonresult.getResCode()) {
                    case "0000":
                        if(isEdit) {
                            CUtils.showToast("任务修改成功！");
                            isEditAdd=false;
                        }else{
                            CUtils.showToast("任务添加成功！");
                            isEditAdd=false;
                        }


                        mTaskActivity.notifyData("任务流程主页");
                        mTaskActivity.getSupportFragmentManager().popBackStackImmediate();
                        if(mCommitpop!=null) {
                            mCommitpop.dismiss();
                        }
                        isFirstEditAdd=false;
                    break;
                    case "0002":
                        if(mCommitpop!=null){
                            mCommitpop.dismiss();
                        }
                        isFirstEditAdd=false;
                    break;
                     case "0003":


                     default:
                         if(mCommitpop!=null){
                             mCommitpop.dismiss();
                         }
                         isFirstEditAdd=false;
            }

        }else if(objdata instanceof WedPlanTypeBean){

            if(mCommitpop!=null) {
                mCommitpop.dismiss();
            }

        }

    }

    @Override
    public void onError(ErrorBean errorBean) {
        if(mCommitpop!=null) {
            mCommitpop.dismiss();
        }
        isFirstEditAdd=false;
        CUtils.showToast("数据请求错误，请重试");


    }


    @Override
    public void notifyData(String pageName) {
        super.notifyData(pageName);
        mTypeList= mTaskActivity.getmTypeList();
        groupPosition = mTaskActivity.getmCurrentGroupPosition();
        dataBean = mTypeList.get(groupPosition);
        weddingProcessClassID= dataBean.getWeddingProcessClassID();
        weddingProcessClassName = mTypeList.get(groupPosition).getWeddingProcessClassName();

        mEditTypeNameTv.setText(weddingProcessClassName);
        mSelecTypeTv.setText(weddingProcessClassName);


    }

    private boolean checEditkword() {
        boolean iswright=false;
        String persons = mAddPersonEt.getText().toString().trim();
        if(!TextUtils.isEmpty(persons)) {
            iswright=true;
        }else{
            CUtils.showToast("人员不能为空");
            return iswright;
        }

        String content = mAddContentEt.getText().toString().trim();
        if( !TextUtils.isEmpty(content)) {
            iswright=true;
        }else{
            CUtils.showToast("流程内容不能为空");
            iswright= false;
        }

        return iswright;

    }


}


